/*
    Copyright 2006 Andrew Wilkinson <andrew@indiegigs.co.uk>

    This file is part of GL2x.

    GL2x is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    GL2x is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with GL2x; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define GLCLIENT
#include "gl_internal.h"

int GL2x_getPixelWidth(GLint internalFormat, GLenum format);

void glTexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels ) {
    void* img = (void*)GP2x_upper_memory_malloc(GL2x_getPixelWidth(internalFormat, type) * width * height);
    memcpy(img, pixels, GL2x_getPixelWidth(internalFormat, type) * width * height);

    struct gltexture* tex = (struct gltexture*)GP2x_upper_memory_malloc(sizeof(struct gltexture));

    tex->dim = 2;
    tex->width = width;
    tex->height = height;
    tex->pixels = img;

    GP2x_postMessage(SET_TEXTURE, (unsigned long)tex, 0);
}

void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels) {
    fprintf(stderr, "glTexSubImage2D not yet implemented.\n");
}

int GL2x_getPixelWidth(GLint internalFormat, GLenum format) {
    int colours, byte;
    switch(internalFormat) {
    case 1:
    case 2:
    case 3:
    case 4:
        colours = internalFormat;
        break;
    case GL_RGB:
        colours = 3;
        break;
    case GL_RGBA:
        colours = 4;
        break;
    default:
        fprintf(stderr, "Unknown internal image format %i.\n", internalFormat);
        colours = 1;
    }
    switch(format) {
    case GL_UNSIGNED_BYTE:
        byte = 1;
        break;
    default:
        fprintf(stderr, "Unknown image byte format %i.\n", format);
        byte = 1;
    }
    return colours * byte;
}
